//
//  ViewController.m
//  搜索_关键字高亮
//
//  Created by 曹曹 on 16/4/25.
//  Copyright © 2016年 曹曹. All rights reserved.
//

#import "ViewController.h"

NS_ASSUME_NONNULL_BEGIN
@interface ViewController () <UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating>

@property (nonatomic, retain) NSMutableArray *arrOfSeachBoxes;/**< 搜索范围 */
@property (nonatomic, retain) NSMutableArray *arrOfSeachResults;/**< 搜索结果 */
@property (nonatomic, retain) UISearchController *searchController;
@property (nonatomic, retain) UITableView *tableView;

@end
NS_ASSUME_NONNULL_END

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self handleData];
    [self createView];
}

- (void)handleData {
    // 解析数据
    NSString *path = [[NSBundle mainBundle] pathForResource:@"heros" ofType:@"txt"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    self.arrOfSeachBoxes = [NSMutableArray array];
    // 将搜索范围的内容放入数组
    for (NSDictionary *dic in result) {
        [self.arrOfSeachBoxes addObject:dic[@"nick"]];
    }
}

- (void)createView {
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];/**< nil表示在当前页面显示搜索结果 */
    self.searchController.searchBar.frame = CGRectMake(0, 44, 0, 44);
    // 基本属性.
    self.searchController.dimsBackgroundDuringPresentation = false;/**< 是否需要在输入搜索内容时变暗 */
    self.searchController.searchBar.showsCancelButton = YES;/**< 取消按钮 */
    self.searchController.searchResultsUpdater = self;/**< 显示搜索结果的VC */
    self.searchController.active = YES;/**< 搜索结果显示 */
    // tableView
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, self.view.bounds.size.height - 20)
                                                  style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"pool"];
    self.tableView.tableHeaderView = self.searchController.searchBar;
}

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    self.arrOfSeachResults = [NSMutableArray array];
    // 获取关键字
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", searchController.searchBar.text];
    // 用关键字过滤范围数组, 将过滤后的内容放入结果数组
    self.arrOfSeachResults = [[self.arrOfSeachBoxes filteredArrayUsingPredicate:predicate] mutableCopy];
    // 完成数据的过滤和存储后刷新tableView.
    [self.tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // 显示搜索结果时
    if (self.searchController.active) {
        return self.arrOfSeachResults.count;
    }
    return self.arrOfSeachBoxes.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pool"];
    // 显示搜索结果时
    if (self.searchController.active) {
        // 原始搜索结果字符串.
        NSString *originResult = self.arrOfSeachResults[indexPath.row];
        // 获取关键字的位置
        NSRange range = [originResult rangeOfString:self.searchController.searchBar.text];
        // 转换成可以操作的字符串类型.
        NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:originResult];
        // 添加属性
        [attribute addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:range];
        [attribute addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
        // 将带属性的字符串添加到cell.textLabel上.
        [cell.textLabel setAttributedText:attribute];
        cell.textLabel.text = self.arrOfSeachResults[indexPath.row];
    } else {
        cell.textLabel.text = self.arrOfSeachBoxes[indexPath.row];
    }
    return cell;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
